import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

import 'base_plugin.dart';
import 'messages.g.dart';

void main(List<String>? args) {
  print("args=$args");
  runApp(MyApp(args: args ?? []));
}

class MyApp extends StatelessWidget {
  final List<String> args;

  const MyApp({super.key, required this.args});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    print("MyApp=build");
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(primarySwatch: Colors.blue),
      home: RouterPage(args: args),
      onGenerateRoute: (settings) {
        switch (settings.name) {
          case '/':
            return MaterialPageRoute(
              builder: (_) => MyHomePage(title: "第一个页面"),
            );
          case '/page2':
            return MaterialPageRoute(builder: (_) => SecondPage());
          default:
            return null;
        }
      },
    );
  }
}

class RouterPage extends StatefulWidget {
  final List<String> args;

  const RouterPage({super.key, required this.args});

  @override
  State<RouterPage> createState() => _RouterPageState();
}

class _RouterPageState extends State<RouterPage> implements FlutterMessageApi {
  late String args2;

  @override
  void initState() {
    super.initState();
    FlutterMessageApi.setUp(this);
  }

  @override
  String native2Flutter(String message, int type) {
    print("native2Flutter=$message $type");
    setState(() {
      args2 = message;
    });

    return "我是原生调用flutter方法返回的值=》native2Flutter";
  }

  @override
  Future<String> native2FlutterAsync(String message, int type) {
    args2 = message;
    print("native2Flutter=$message $type");
    return Future.value("我是原生调用flutter方法返回的值=》native2FlutterAsync");
  }

  @override
  Widget build(BuildContext context) {
    // final value = widget.args.isNotEmpty ? widget.args[0] : "/";
    if (args2.isEmpty||!args2.contains("#")) {
      return MyHomePage(title: "首页");
    }
    final value = args2.split("#").first;
    switch (value) {
      case '/page2':
        return SecondPage();
    }
    print("_RouterPageState=build");
    return MyHomePage(title: "首页");
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage>  {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    print("_MyHomePageState=build");
    return Scaffold(
      appBar: AppBar(title: Text(widget.title), leading: BackButton(onPressed:(){
        BasePlugin.flutter2NativeAsync("closeFlutter", 1).then((
            value,
            ) {
           print("flutter2NativeAsync=$value");
        });
      },)),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            TextButton(
              onPressed: () {
                Navigator.of(context).pushNamed("/page2");
              },
              child: Text('goPage2'),
            ),
            const Text('You have pushed the button this many times:'),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headlineMedium,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }

}

class SecondPage extends StatelessWidget {
  const SecondPage({super.key});

  @override
  Widget build(BuildContext context) {
    print("SecondPage=build");
    return Scaffold(
      appBar: AppBar(title: Text("SecondPage")),
      body: Center(
        child: TextButton(
          onPressed: () {
            if (Navigator.of(context).canPop()) {
              Navigator.of(context).pop();
            }else{
              BasePlugin.flutter2NativeAsync("closeFlutter", 1).then((
                  value,
                  ) {
                print("flutter2NativeAsync=$value");
              });
            }
          },
          child: Text('关闭'),
        ),
      ),
    );
  }
}


class StudyChannel extends StatefulWidget {
  const StudyChannel({super.key});

  @override
  State<StudyChannel> createState() => _StudyChannelState();
}

class _StudyChannelState extends State<StudyChannel> {
  MethodChannel methodChannel = const MethodChannel('base_plugin');
  EventChannel eventChannel = const EventChannel('base_plugin');
  static const basicMessageChannel = BasicMessageChannel<String>('base_plugin', StringCodec());  @override
  void initState() {
    super.initState();
    //只接收
    eventChannel.receiveBroadcastStream().listen((value){

    });

    //监听
    methodChannel.setMethodCallHandler((call){
      call.method == "getData" ? print("getData") : print("method=$call");
      return Future.value("methodChannel=$call");
    });
    //执行，相当于发送
    methodChannel.invokeListMethod("getData");

    //发送
    basicMessageChannel.send("data");
    //监听
    basicMessageChannel.setMessageHandler((message){
      return Future.value("basicMessageChannel=$message");
    });

  }
  @override
  Widget build(BuildContext context) {
    return const Placeholder();
  }
}


